package com.xiexie.seckill.controller;

import com.xiexie.seckill.pojo.User;
import com.xiexie.seckill.service.IGoodsService;
import com.xiexie.seckill.service.IUserService;
import com.xiexie.seckill.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    // thymeleaf 模板引擎
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     *  没用分布式session之前
     * @param session
     * @param ticket
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("toList")
    public String toList(HttpSession session,
                         @CookieValue("userTicket") String ticket, Model model,
                         HttpServletRequest request, HttpServletResponse response) {

        if (StringUtils.isEmpty(ticket)) {
            return "login";
        }
        //User user = (User) session.getAttribute(ticket);
        User user = userService.getUserByCookie(ticket, request, response);
        if (null == null) {
            return "login";
        }
        session.setAttribute("user", user);
        model.addAttribute("user", user);
        return "goodsList";
    }

    /**
     * 分布式session之后
     * 改造页面缓存
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "toList2", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList2(Model model, User user,
                          HttpServletRequest request, HttpServletResponse response) {

        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());

        // redis中获取页面信息
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String goodsListHtml = (String) valueOperations.get("goodsList");
        if (!StringUtils.isEmpty(goodsListHtml)) {
            return goodsListHtml;
        }
        // 如果不存在 则渲染页面并放入缓存中
        WebContext webContext =
                new WebContext(request, response,
                        request.getServletContext(),
                        request.getLocale(), model.asMap());

        goodsListHtml = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if (!StringUtils.isEmpty(goodsListHtml)) {
            valueOperations.set("goodsList", goodsListHtml, 60, TimeUnit.SECONDS);
            return goodsListHtml;
        }
        //return "goodsList";
        return null;
    }

    /**
     * 商品详情页面
     * 做url层面的缓存（但是实际还是做的页面缓存，把所有的id数据做一遍缓存）
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model, User user, @PathVariable Long goodsId,
                           HttpServletRequest request, HttpServletResponse response) {

        // 放入缓存中
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String goodsDetailHtml = (String) valueOperations.get("goodsDetail" + goodsId);
        if (!StringUtils.isEmpty(goodsDetailHtml)) {
            return goodsDetailHtml;
        }

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        // 秒杀状态
        int secKillStatus = 0;
        // 秒杀倒计时
        int remainSeconds = 0;
        if (nowDate.before(startDate)) {
            // 秒杀还未开始
            secKillStatus = 0;
            remainSeconds = ((int)((startDate.getTime() - nowDate.getTime())/1000));
        } else if (nowDate.after(endDate)) {
            // 秒杀结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            // 秒杀中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("goods", goodsVo);
        // 如果不存在 则渲染页面并放入缓存中
        WebContext webContext =
                new WebContext(request, response,
                        request.getServletContext(),
                        request.getLocale(), model.asMap());
        goodsDetailHtml = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        if (!StringUtils.isEmpty(goodsDetailHtml)) {
            valueOperations.set("goodsDetail" + goodsId, goodsDetailHtml,  60, TimeUnit.SECONDS);
            return goodsDetailHtml;
        }
        //return "goodsDetail";
        return null;
    }
}
